const path = require('path');
const fs = require('fs');

class OutputSourcePlugin {
    constructor({ output }) {
        this.output = output;
    }
    apply(compiler) {
        compiler.hooks.done.tap(
            'OutputSourcePlugin',
            ({ compilation }) => {
                let outputPath = compilation.compiler.outputPath;
                [...compilation.fileDependencies].forEach(file => {
                    if (!file.includes('node_modules')) {
                        let targetPath = path.resolve(
                                path.resolve(outputPath, typeof this.output === 'function' ? this.output(file) : this.output),
                                path.relative(path.resolve(__dirname, '../'), file),
                            ), targetDir = path.resolve(targetPath, '../');

                        mkdir(targetDir);

                        // fs.writeFileSync(targetPath, fs.readFileSync(file));
                        fs.copyFileSync(file, targetPath);
                    }
                });
            },
        );
    }
}

function mkdir(dir) {
    if (!fs.existsSync(dir)) {
        let parentDir = path.resolve(dir, '../');
        mkdir(parentDir);
        fs.mkdirSync(dir);
    }
}

module.exports = OutputSourcePlugin;